import { Page } from '@playwright/test';

/**
 * 是否已经登录
 *
 * @author chitanda
 * @date 2022-04-14 15:04:21
 * @export
 * @param {Page} p
 * @return {*}  {Promise<boolean>}
 */
export async function isLogin(p: Page): Promise<boolean> {
  // 判断是否登录
  return p.evaluate(() => {
    // 获取cookie方法
    const getCookie = (name: string): string | null => {
      const reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
      const arr = document.cookie.match(reg);
      if (arr && arr.length > 1) {
        return unescape(arr[2]);
      }
      return null;
    };
    // 查看token是否存在
    const token = getCookie('ibzuaa-token');
    if (token) {
      return true;
    }
    return false;
  });
}

/**
 * Studio 登录用户
 *
 * @author chitanda
 * @date 2022-04-15 09:04:14
 * @export
 * @param {Page} p
 * @param {string} username
 * @param {string} password
 * @return {*}  {Promise<boolean>}
 */
export async function login(p: Page, username: string, password: string): Promise<boolean> {
  const judge = await isLogin(p);
  if (judge === false) {
    try {
      // 等待跳转登录页
      await p.waitForSelector('#username', { timeout: 5000 });
    } catch (err) {
      const judge = await isLogin(p);
      if (judge) {
        return true;
      }
      return login(p, username, password);
    }
    // 等待
    await p.waitForTimeout(300);
    await p.type('#username', username);
    await p.type('#password', password);
    await p.click('input[name=submit]');
    // 等待跳转回去
    await p.waitForNavigation();
    return true;
  }
  return false;
}
